#pragma once

#include <iostream>
#include <string>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>

#include "Log.hpp"
#include "InetAddr.hpp"


enum
{
    SOCKET_ERROR = 1,
    BIND_ERROR,
    LISTEN_ERROR
};

const static int defaultsockfd = -1;
const static int backlog = 16;

class TcpServer
{
public:
    TcpServer(int port)
    : _port(port)
    , _listensock(defaultsockfd)
    {}

    void InitServer()
    {
        _listensock = socket(AF_INET, SOCK_STREAM, 0);
        if(_listensock < 0)
        {
            LOG(FATAL, "create socket error");
            exit(SOCKET_ERROR);
        }
        LOG(DEBUG, "sockrt create success, sockfd: %d", _listensock);

        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = INADDR_ANY;

        int n = bind(_listensock, (struct sockaddr*)&local, sizeof(local));
        if(n < 0)
        {
            LOG(FATAL, "bind error");
            exit(BIND_ERROR);
        }

        n = ::listen(_listensock, backlog);
        if(n < 0)
        {
            LOG(FATAL, "listen error");
            exit(LISTEN_ERROR);
        }
    }
    void Service(int sockfd, InetAddr client)
    {
        LOG(DEBUG, "get a new link %s:%d", client.Ip().c_str(), client.Port());
        
        std::string clientaddr = "[" + client.Ip() + ":" + std::to_string(client.Port()) + "]# ";
        while(true)
        {
            char inbuffer[1024];
            int n = read(sockfd, inbuffer, sizeof(inbuffer) - 1);
            if(n > 0)
            {
                inbuffer[n] = 0;
                std::cout << clientaddr <<  inbuffer << std::endl;
                
                std::string echo_string = "[server echo]# ";
                echo_string += inbuffer;
                write(sockfd, echo_string.c_str(), echo_string.size());
            }
            else if(n == 0)
            {
                LOG(INFO, "%s quit", clientaddr.c_str());
                break;
            }   
            else
            {
                LOG(ERROR, "read error");
                break;
            }
        }
        close(sockfd);  // 处理文件描述符泄露
    }
    void Loop()
    {
        _isrunning = true;
        while(_isrunning)
        {
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            int sockfd = ::accept(_listensock, (struct sockaddr*)&peer, &len);
            if(sockfd < 0)
            {
                LOG(WARNING, "accept error");
                continue;
            }
            Service(sockfd, InetAddr(peer));
        }
        _isrunning = false;
    }

    ~TcpServer()
    {
        if(_listensock > defaultsockfd) ::close(_listensock);
    }

private:
    uint16_t _port;
    int _listensock;
    bool _isrunning;
};